package com.siriframe.user.backup.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.siriframe.user.backup.enums.BackUpDataSceneEnum;
import com.siriframe.user.backup.rule.UserBackUpDataRule;
import com.siriframe.user.dao.UserBackDao;
import com.siriframe.user.dao.UserDao;
import com.siriframe.user.entity.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UserForwardHandler extends AbstractBackUpDataHandler<User, UserBackUpDataRule> {

    /**
     * 归档规则，可以配合nacos动态配置
     */
    private String sysUserBackupRuleStr;

    private Boolean stopFlag;

    @Resource
    private UserDao userDao;

    @Resource
    private UserBackDao userBackDao;

    @Override
    public Boolean needStop() {
        return stopFlag;
    }

    @Override
    public BackUpDataSceneEnum getScene() {
        return BackUpDataSceneEnum.USER_FORWARD;
    }

    @Override
    public List<User> queryData(UserBackUpDataRule rule) {
        User sysUser = new User();
        List<User> sysUserList = userDao.queryAll(sysUser);
        return sysUserList;
    }

    @Override
    public void insertData(List<User> sysUserList) {
        userBackDao.insertBatch(sysUserList);
    }

    @Override
    public void deleteData(List<User> dataList) {
        List<Long> ids = dataList.stream().map(User::getId).collect(Collectors.toList());
        userDao.batchDelete(ids);
    }

    @Override
    public UserBackUpDataRule getRule() {
        UserBackUpDataRule backUpRule = JSON.parseObject(sysUserBackupRuleStr, UserBackUpDataRule.class);
        Preconditions.checkNotNull(backUpRule, "归档规则不能为空！");
        Preconditions.checkNotNull(backUpRule.getQuerySize(), "查询数量不能为空！");
        Preconditions.checkNotNull(backUpRule.getBeginId(), "beginId不能为空！");
        Long endId = backUpRule.getBeginId() + backUpRule.getQuerySize();
        backUpRule.setEndId(endId);
        return backUpRule;
    }

    @Override
    public UserBackUpDataRule changeOffSet(UserBackUpDataRule backupDataRule) {
        backupDataRule.setBeginId(backupDataRule.getEndId());
        Long endId = backupDataRule.getBeginId() + backupDataRule.getQuerySize();
        backupDataRule.setEndId(endId);
        return backupDataRule;
    }

}